<template>
  <div class="course-series">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>课程系列</span>
          <el-button type="primary" @click="handleCreate">新增系列</el-button>
        </div>
      </template>

      <el-table :data="tableData" v-loading="loading">
        <el-table-column label="系列名称" prop="name" />
        <el-table-column label="版本数量" prop="versionCount" width="100" />
        <el-table-column label="课程数量" prop="courseCount" width="100" />
        <el-table-column label="创建时间" prop="createdAt" width="180" />
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" @click="handleViewVersions(row)">查看版本</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="系列名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入系列名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { courseService } from '../../services/course'
import { ElMessageBox } from 'element-plus'
import { showSuccess, showError } from '../../utils/message'

const router = useRouter()
const loading = ref(false)
const tableData = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentId = ref('')

const formData = ref({
  name: ''
})

const formRules = {
  name: [
    { required: true, message: '请输入系列名称', trigger: 'blur' }
  ]
}

const handleCreate = () => {
  dialogTitle.value = '新增系列'
  dialogVisible.value = true
  currentId.value = ''
  formData.value = { name: '' }
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑系列'
  dialogVisible.value = true
  currentId.value = row.id
  formData.value = { name: row.name }
}

const handleViewVersions = (row) => {
  router.push({
    path: `/exam/series/${row.id}/versions`,
    query: { seriesName: row.name }
  })
}

const handleSubmit = async () => {
  try {
    // TODO: 完成新增/编辑课程系列的API调用
    await loadSeriesList()
    dialogVisible.value = false
    showSuccess(currentId.value ? '编辑成功' : '新增成功')
  } catch (error) {
    showError(currentId.value ? '编辑失败' : '新增失败')
    console.error(error)
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除课程系列"${row.name}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    // TODO: 完成删除课程系列的API调用
    await loadSeriesList()
    showSuccess('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      showError('删除失败')
      console.error(error)
    }
  }
}

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const handleSizeChange = (val) => {
  pageSize.value = val
  loadSeriesList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadSeriesList()
}

// 修改加载系列列表
const loadSeriesList = async () => {
  try {
    loading.value = true
    const { data, total: totalCount } = await courseService.getSeriesList(
      currentPage.value, 
      pageSize.value
    )
    tableData.value = data
    total.value = totalCount
  } catch (error) {
    showError('加载课程系列失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadSeriesList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
